package com.spmsys.controller.auth;

import com.alibaba.fastjson.JSONObject;
import com.spmsys.service.Auth;
import com.spmsys.util.ServletUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;

@WebServlet(name = "Login", value = "/controller/auth/Login")
public class Login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(@NotNull HttpServletRequest req, @NotNull HttpServletResponse resp) throws ServletException, IOException {
        JSONObject requestData;
        JSONObject responseData = new JSONObject();
        PrintWriter printWriter = resp.getWriter();
        HttpSession httpSession = req.getSession();
        try {
            //获取当前时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
            //设置字符集、接受所有跨域请求、设置时间
            resp.setContentType("application/json;charset=utf-8");
            resp.setHeader("Access-Control-Allow-Origin", "*");
            resp.setHeader("Access-Control-Allow-Methods", "*");
            resp.setHeader("Access-Control-Allow-Headers", "*");
            resp.setHeader("Date", simpleDateFormat.format(Calendar.getInstance().getTime()));
            //获取请求
            requestData = ServletUtil.getRequestBody(req);
            if (requestData == null) {
                throw new RuntimeException("参数错误");
            }
            //处理请求
            String email = requestData.getString("email");
            String phone = requestData.getString("phone");
            String password = requestData.getString("password");
            if (!(email != null || phone != null)) {
                throw new RuntimeException("email和phone必填其一");
            }
            if (password == null) {
                throw new RuntimeException("password为必填参数");
            }
            Auth auth = new Auth();
            JSONObject loginResult = auth.login(email, phone, password);
            if (loginResult.get("data") == null) {
                throw new RuntimeException(loginResult.getString("errorMessage"));
            }
            //响应请求
            httpSession.setAttribute("auth", auth);
            httpSession.setMaxInactiveInterval(30 * 24 * 60 * 60);
            Cookie cookieId = new Cookie("id", httpSession.getId());
            Cookie cookieAuthorization = new Cookie("authorization", auth.getToken(null));
            cookieId.setPath("/");
            cookieAuthorization.setPath("/");
            cookieId.setMaxAge(30 * 24 * 60 * 60);
            cookieAuthorization.setMaxAge(30 * 24 * 60 * 60);
            resp.addCookie(cookieId);
            resp.addCookie(cookieAuthorization);
            responseData.put("data", new JSONObject() {{
                put("id", httpSession.getId());
                put("authorization", auth.getToken(null));
            }});
        } catch (Exception e) {
            responseData.put("errorCode", "LOGIN_FAILED");
            responseData.put("errorMessage", e.getMessage());
        }
        printWriter.println(responseData);
        printWriter.close();
    }
}
